//
//  AutographController.swift
//  newShaohuoRen
//
//  Created by hujinbiao on 2018/3/24.
//  Copyright © 2018年 hujinbiao. All rights reserved.
//

import UIKit
import SwiftProgressHUD

protocol AutographControllerDelegate {
    func autographController(signature:String)
}

class AutographController: UITableViewController {
    
    @IBOutlet weak var autoTextField: UITextView!
    
    var delegate : AutographControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "签名"

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(saveBtnAction))
        
        autoTextField.delegate = self
        
    }
    
    //保存
    @objc func saveBtnAction() -> Void {
        
        if autoTextField.text.isEmpty||autoTextField.text.hasPrefix(" ") {
            SwiftProgressHUD.showOnlyText("输入内容不合法")
            return
        }
        
        requestUpdateUserInfo(signature: autoTextField.text!)
    }
    
    func requestUpdateUserInfo(signature:String) -> Void {
        
        //要加密的数据
        let param = ["command":"updateUserInfo","uid":UserTicketModel.sharedInstance.uid ?? "","token":UserTicketModel.sharedInstance.token ?? "","signature":signature,"app_name":"shr"]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"UserInfo"], successed: { (resultDict) in
            
            SwiftProgressHUD.showOnlyText("操作成功")
            let data = resultDict["data"] as! [String:AnyObject]
            let signature = data["signature"] as! String
            self.delegate?.autographController(signature: signature)
            self.navigationController?.popViewController(animated: true)
        })
    }
}

extension AutographController {
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}

extension AutographController : UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        let textVStr = textView.text as NSString
        if (textVStr.length >= 50) {
            let str = textVStr.substring(to: 50)
            textView.text = str
        }
    }
}
